package org.example.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class CharacterEncodingFilter implements Filter {
    private String encoding;
    private String contentType;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }

        // 添加Content-Type设置，包含字符编码
        contentType = filterConfig.getInitParameter("contentType");
        if (contentType == null) {
            contentType = "text/html; charset=" + encoding;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 设置请求编码
        request.setCharacterEncoding(encoding);

        // 设置响应编码和Content-Type
        response.setCharacterEncoding(encoding);
        response.setContentType(contentType);

        // 如果是HTTP响应，还可以设置Header
        if (response instanceof HttpServletResponse) {
            ((HttpServletResponse) response).setHeader("Content-Type", contentType);
        }

        // 传递请求
        chain.doFilter(request, response);
    }
}